package com.cn.studey.controller;

import com.cn.studey.annotations.UserLog;
import com.cn.studey.common.ResultCode;
import com.cn.studey.entity.User;
import com.cn.studey.entity.dto.LoginDto;
import com.cn.studey.entity.vo.LoginVo;
import com.cn.studey.entity.vo.ResultVO;
import com.cn.studey.service.TokenService;
import com.cn.studey.service.UserService;
import com.cn.studey.utils.ApartLogUtils;
import com.cn.studey.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author mjy
 * @date 2021/12/27
 * @description
 */
@RestController
@RequestMapping("/login")
public class LoginController {


    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;


    /**
     * 流程
     * 1.校验参数，以及账号用户名的正确性
     * 2.同步用户地区，以及语言
     * 3.根据用户id生成token(生成签名)
     * 4.创建vo对象返回前端
     * 返回的token(在登陆验证之后，请带入请求头中)
     *
     * @param loginDto
     * @return
     */
    @UserLog(describe = "")
    @RequestMapping("/login")
    public ResultVO<LoginVo> login(@RequestBody LoginDto loginDto) {
        logger.info("login param={}" + loginDto.toString());
        if (StringUtils.isBlank(loginDto.getAccount()) || StringUtils.isBlank(loginDto.getPwd())) {
            return ResultVO.fail(ResultCode.VALIDATE_FAILED);
        }
        User user = userService.getUserInfoByAccountAndPwd(loginDto.getAccount(), loginDto.getPwd());
        if (user == null) {
            return ResultVO.fail(ResultCode.USERNAME_PASSWORD_ERROR);
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setLanguage(loginDto.getAccount());
        newUser.setArea(loginDto.getArea());
        newUser.setLoginTime(new Date());
        userService.updateUserById(newUser);
        String token = tokenService.createToken(user.getId());
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        /**
         * 通过用户数据修改描述值
         * 此时不建议通过反射修改注解描述值
         * 1.反射影响反应性能
         * 2.增加代码的耦合度
         * 3.这里为学习反射添加,最好从设计上就避免此操作
         */
        Method method = null;
        try {
            method = LoginController.class.getMethod("login", LoginDto.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        String describe=user.getAccount().concat("登录").concat("登录时间为").concat(DateUtils.format(new Date(),DateUtils.dateFormat4));
        ApartLogUtils.modifyAnnotation(method,describe);
        return ResultVO.ok(loginVo);
    }


}
